import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import { RedisService } from '../redis/redis.service';
import { CustomException, ErrorCode } from 'src/common/exceptions/custom.exception';

@Injectable()
export class CaptchaService {
  constructor(private readonly redisService: RedisService) {}
  private expireIn: number = 86400; //24小时

  /** 生成 captcha key */
  private getCaptchaKey(captchaId: number) {
    return `captcha:${captchaId}`;
  }

  /** 生成验证码 */
  public async genCaptcha() {
    const captcha = svgCaptcha.create({
      size: 4,
      fontSize: 40,
      width: 80,
      height: 40,
      background: '#fff',
      color: true,
    });
    const captchaId = await this.redisService.genIncrKey('captchaId'); //自增操作
    await this.redisService.setStringWithEx(this.getCaptchaKey(captchaId), this.expireIn, captcha.text); // 值存 redis
    return {
      captcha: captcha.data,
      captchaId,
    };
  }

  /** 检验验证码 */
  public async validateCaptcha(captchaId: number, captcha: string) {
    const capt = await this.redisService.getString(`captcha:${captchaId}`);
    // 过期或不存在
    if (!capt) {
      return new CustomException(ErrorCode.ERR_10003);
    }
    // 从redis删除
    await this.redisService.delString(this.getCaptchaKey(captchaId));
    return captcha === capt;
  }
}
